package com.hongye.gateway.config;


import com.hongye.common.utils.JwtUtil;
import com.hongye.common.utils.StaticConfig;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("执行过滤");
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        //除了登陆和发送验证码 其他的功能全部拦截
        if (StaticConfig.PASS_PATH.contains(uri.getPath())) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().get("token").get(0);
        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null){
//            String o = String.valueOf(claims.get(StaticConfig.LOGIN_ROLE));
//            Long id = Long.valueOf(claims.getId());
//
//            LoginUserVo loginUserVo = new LoginUserVo();
//            loginUserVo.setUserId(id);
//            loginUserVo.setRole(o);
//
//            String s = JSONObject.toJSONString(loginUserVo);
//            request.getHeaders().set(StaticConfig.USER_THREADLOCAL,s);
            return chain.filter(exchange);
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
